<?php
class DigUser_Model_Account extends Dig_Model_Abstract 
{
    /**
     * The default table name
     */
    protected $_name = 'users';

    /**
     * creates a new, empty user.
     *
     * @return Zend_Db_Table_Row
     */
    public static function createUser()
    {
        $userModel = new self();
        $row = $userModel->createRow()->save();
        return $row;
    }

    /**
     * this method allows you to quickly rename a user
     * 
     * it expects the user's name to be a space separated string
     * eg: 'forrest lyman'
     * 
     * @param int $id
     * @param string $newName
     * @return Zend_Db_Table_Row
     */
    public static function renameUser($id, $newName)
    {
        $nameParts = explode(' ', $newName);
        if(!is_array($nameParts) || empty($nameParts[0])) {
            throw new DigUser_Exception('Invalid name passed to rename method');
        }
        $userModel = new self();
        $currentUser = $userModel->find($id)->current();
        if($currentUser) {
            $currentUser->first_name = $nameParts[0];
            $currentUser->last_name = $nameParts[1];
            $currentUser->save();
            return $currentUser;
        }
    }

    public static function getUsers()
    {
        $userModel = new self();
        $select = $userModel->select();
        $select->order(array('last_name', 'first_name'));
        return $userModel->fetchAll($select);
    }
    
    public function updatePassword($id, $password)
    {
        // fetch the user's row
        $rowUser = $this->find($id)->current();
    
        if($rowUser) {
            //update the password
            $rowUser->password = md5($password);
            $rowUser->save();
        }else{
            throw new Zend_Exception("Password update failed.  User not found!");
        }
    }

    public static function setRole($id, $role)
    {
        $model = new self();
        $user = $model->find($id)->current();
        if($user && in_array($role, DigUser_Service_User::roles())) {
            $user->role = $role;
            $user->save();
            return true;
        }
    }

    public static function listUsersByRole()
    {
        $model = new self();
        $select = $model->select();
        $select->order(array('first_name', 'last_name'));
        $users = $model->fetchAll($select);
        if($users->count() > 0) {
            // fetch the default and set up the standard roles
            foreach (DigUser_Service_User::roles() as $role) {
                $userArray[$role] = array();
            }

            foreach ($users as $user) {
                $key = strtolower($user->role);
                $userArray[$key][] = $user->toArray();
            }
            return $userArray;
        }        
    }

    protected function _setPassword($data) {
        return md5($data['password']);
    }
}
